var cacheUtil = require('../common/utils/cacheUtil');
/**
 * To check the request token
 */
exports.doCheckToken = function (req, res, next) {

    //如果是：（1）不启用Token校验, （2）用户注册，（3）用户登录，（4）app登录,(5)backOffice的服务请求，那么就不需要进行token检查
    if (enableToken != 'Yes'
        || req.url.indexOf('/rest/' + RESTFullServiceVersion + '/users/signup') == 0
        || req.url.indexOf('/rest/' + RESTFullServiceVersion + '/users/appLogin') == 0
        || req.url.indexOf('/rest/' + RESTFullServiceVersion + '/users/login') == 0
        || req.url.indexOf('/rest/' + RESTFullServiceVersion + '/backoffice') == 0) {
        //Pass to next function;
        req.session.user = null;
        next();
    } else {
        logger.debug('Doing the token checking for the request from:\'' + req.ip + '\'on resource \'' + req.url + '\'');
        var tempArray = req.url.split('/');
        var token = tempArray[tempArray.length - 2];
        cacheUtil.cacheGet(token, function (err, result) {
            if (err || result == null) {
                logger.error('There is no valid token for the request - ' + req.url);
                //next('There is no valid token for the request - '+req.url);
                res.json({status: '400', message: 'There is no valid token for the request - ' + req.url});
            } else {
                //把result存入session变量中；
                req.session.user = result;
                logger.debug('Valid token for the request - ' + req.url);

                //Pass to next function;
                next();
            }
        })
    }
}